//
//  VIPWrite.m
//  VIPCODE
//
//  Created by Taurin on 2019/9/11.
//  Copyright © 2019 VIPCODE-Student. All rights reserved.
//

#import "VIPWrite.h"
#import "NSDate+VIPExtension.h"
#import "NSString+VIPDate.h"
#import "VIPPath.h"

@implementation VIPWrite

static NSString *_directoryPath;
static NSString *_filePath;
static const uint DefaultLogSaveTime = 3;

static int _logSaveTime = DefaultLogSaveTime;
+ (void)logSaveTime:(uint)time {
    _logSaveTime = time;
}

+ (void)load {
    [super load];
    
    [self setupFilePath];
    
    [self clearExpiredLog];
}

+ (void)setupFilePath {
    // 创建日期格式化
    NSString *currentTime = [NSDate vip_current:@"yyyy-MM-dd"];
    NSString *fileName = [NSString stringWithFormat:@"%@.log", currentTime];
    
    // 文件目录
    // 获取文稿(Documents) VIPCODE目录
    NSString *logPath = [VIPPath logsPath];
    
    [self setupFilePath:logPath fileName:fileName];
}

+ (void)setupFilePath:(NSString *)path fileName:(NSString *)name {
    _directoryPath = path;
    NSString *filePath = [path stringByAppendingPathComponent:name];
    [self filePath:filePath];
}

+ (void)filePath:(NSString *)filePath {
    if (![filePath isEqualToString:_filePath]) {
        _filePath = filePath;
    }
}

/**
 *  追加写入字符串到指定文件
 *
 *  @param log        待写入的日志
 */
+ (BOOL)writeLog:(NSString *)log {
    // 获取当前日期做为文件名
    NSString *writeLog = [NSString stringWithFormat:@"%@ %@\n", [NSDate vip_current:nil], log];
    return [self writeLog:writeLog filePath:_filePath];
}

/**
 *  追加写入字符串到指定文件
 *
 *  @param format        待写入的日志
 */
+ (void)writeLogWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2) {
    va_list ap;
    va_start (ap, format);
    NSString *logString = [[NSString alloc] initWithFormat:format arguments:ap];
    va_end (ap);
    
    [self writeLog:logString];
}

/**
 *  追加写入字符串到指定文件
 *
 *  @param log        待写入的日志
 *  @param filePath   文件路径
 */
+ (BOOL)writeLog:(NSString *)log filePath:(NSString *)filePath {
    return [self write:log filePath:filePath];
}

/**
 *  追加写入字符串到指定文件
 *
 *  @param filePath   文件路径
 *  @param format     格式化的log
 */
+ (void)writeLogWithFilePath:(NSString *)filePath logWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(2,3) {
    va_list ap;
    va_start (ap, format);
    NSString *logString = [[NSString alloc] initWithFormat:format arguments:ap];
    va_end (ap);
    [self writeLog:logString filePath:filePath];
}

/**
 *  追加写入字符串到指定文件
 *
 *  @param text       待写入的文本
 *  @param filePath   文件路径
 */
+ (BOOL)write:(NSString *)text filePath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:filePath]) { // 如果不存在,则说明是第一次运行这个程序，那么建立这个文件夹
        NSString *directoryPath = [filePath stringByDeletingLastPathComponent];
        [fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
        return [text writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
    }
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:_filePath];
    [fileHandle seekToEndOfFile];  // 将节点跳到文件的末尾
    NSData* stringData = [text dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:stringData]; // 追加写入数据
    [fileHandle closeFile];
    return YES;
}

/**
 *  清空过期的日志
 */
+ (void)clearExpiredLog {
    // 获取日志目录下的所有文件
    NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:_directoryPath error:nil];
    for (NSString* file in files) {
        // NSLog(@"file: %@", file);
        NSString *fileName = [file stringByDeletingPathExtension];
        if (fileName.length == 0) continue;
        
        NSDate *startDate = [fileName vip_dateFormatter:@"yyyy-MM-dd"];
        if (startDate == nil) continue;
        
        NSDate *endDate = [NSDate vip_currentDate:@"yyyy-MM-dd"];
        
        NSCalendar *calendar = [NSCalendar currentCalendar];
        //比较的结果是NSDateComponents类对象
        NSDateComponents *delta = [calendar components:NSCalendarUnitDay fromDate:startDate toDate:endDate options:0];
        // NSLog(@"%ld",(long)delta.day);
        if (delta.day >= _logSaveTime) {
            // 删除该文件
            NSString *filePath = [NSString stringWithFormat:@"%@/%@",_directoryPath,file];
            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
            // NSLog(@"[%@]日志文件已被删除！",file);
        }
    }
}

@end
